package com.fuchuang.seckillsystem.utils;

import com.fuchuang.seckillsystem.exception.GlobalException;
import com.fuchuang.seckillsystem.vo.RespBeanEnum;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.ExpiredJwtException;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import lombok.Data;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Component
@Data
public class JsonWebTokenUtils {
    
    @Value("${jwt.secret}")
    private String secret;
    
    @Value("${jwt.expiration}")
    private Long expiration;
    
    @Value("${jwt.header}")
    private String header;
    
    @Value(("${jwt.refresh_expiration}"))
    private Long refresh_expiration;
    
    
    /**
     * 生成令牌
     */
    public String generateToken(String username) {
        Map<String, Object> claims = new HashMap<>();
        claims.put("sub", username);
        claims.put("create", new Date());
        return generateToken(claims);
    }
    
    /**
     * 从claims生成令牌
     */
    private String generateToken(Map<String, Object> claims) {
        Date expirationDate = new Date(System.currentTimeMillis() + expiration);
        return Jwts.builder().setClaims(claims)
                .setExpiration(expirationDate)//设置过期时间
                .signWith(SignatureAlgorithm.HS512, secret)
                .compact();
    }
    
    /**
     * @param username 用户名称
     * @return 生成RefreshToken
     */
    public String generateRefreshToken(String username) {
        Map<String, Object> claims = new HashMap<>();
        claims.put("sub", username);
        claims.put("create", new Date());
        //设置过期时间为七天；
        Date expirationDate = new Date(System.currentTimeMillis() + refresh_expiration);
        return Jwts.builder().setClaims(claims)
                .setExpiration(expirationDate)
                .signWith(SignatureAlgorithm.HS512, secret)
                .compact();
    }
    
    /**
     * 从令牌中获取用户名
     *
     * @param token 令牌
     * @return 用户名
     */
    public String getUsernameFromToken(String token) {
        String username;
        try {
            Claims claims = getClaimsFromToken(token);
            username = claims.getSubject();
        } catch (ExpiredJwtException e) {
            username = null;
        }
        return username;
    }
    
    
    /**
     * 从令牌中获取数据声明，
     *
     * @param token 令牌
     * @return 数据声明
     */
    private Claims getClaimsFromToken(String token) {
        return Jwts.parser().setSigningKey(secret).parseClaimsJws(token).getBody();
    }
    
    /**
     * 判断令牌是否过期
     *
     * @param token 令牌
     * @return 是否过期
     */
    public Boolean isTokenExpired(String token) {
        try {
            Claims claims = getClaimsFromToken(token);
            Date expiration = claims.getExpiration();
            return expiration.before(new Date());
        } catch (Exception e) {
            return true;
        }
    }
    
    /**
     * 验证令牌
     *
     * @param token       令牌
     * @param userDetails 用户
     * @return 是否有效
     */
    public Boolean validateToken(String token, UserDetails userDetails) {
        try {
            String username = getUsernameFromToken(token);
            return (username.equals(userDetails.getUsername()) && !isTokenExpired(token));
        } catch (Exception e) {
            throw new GlobalException(RespBeanEnum.TOKEN_ERROR);
        }
        
    }
    
    /**
     * 刷新refreshToken
     *
     * @param refreshToken 刷新令牌
     */
    public String getNewRefreshToken(String refreshToken) {
        try {
            Claims claims = getClaimsFromToken(refreshToken);
            Date expiration = claims.getExpiration();
            //如果refreshToken距过期时间不足1小时，刷新refreshToken
            if (expiration.getTime() - System.currentTimeMillis() < 1000 * 60 * 60 * 12) {
                return generateRefreshToken(getUsernameFromToken(refreshToken));
            }
            return refreshToken;
        } catch (Exception e) {
            return refreshToken;
        }
    }
    
    
}

